﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DAL;
using System.Data;

public partial class Dang_Nhap : System.Web.UI.Page
{
    DigitalWorldDataContext db = new DigitalWorldDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lbSelected.Text = "0 item(s)";
            LoadCountItem();
        }
    }

    void LoadCountItem()
    {
        DataTable dtCart = Session["Cart"] as DataTable;
        if (dtCart.Rows.Count > 0)
        {
            lbSelected.Text = dtCart.Compute("SUM(Quantity)", "").ToString() + " item(s)";
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (TestUser() == false)
        {
            lblThongBao.Text = "<br />Tài khoản hoặc password không đúng";
        }
        else
        {
            var danhsach = db.customers.SingleOrDefault
                   (cu => cu.username.Equals(txtUserName.Text) && cu.password.Equals(MaHoa(txtPassword.Text)));
            if (ckRemberLogin.Checked == true)
            {
                HttpCookie ck = new HttpCookie("www.digital.com");
                ck["Username"] = txtUserName.Text;
                ck["ID"] = danhsach.customerid.ToString();
                ck.Expires = DateTime.Now.AddSeconds(30);
                Session["Username"] = ck["Username"];
                Session["ID"] = ck["ID"];
                Response.Cookies.Add(ck);
            }
            else
            {
                Session["Username"] = txtUserName.Text;
                Session["ID"] = danhsach.customerid;
            }
            Response.Redirect("~/Default.aspx");    
        }
    }

    bool TestUser()
    {
        string username = txtUserName.Text;
        //string password = txtPassword.Text;
        string password = MaHoa(txtPassword.Text);

        var danhsach = db.customers.SingleOrDefault
            (cu => cu.username.Equals(username) && cu.password.Equals(password));
        if (danhsach != null)
            return true;
        return false;
    }

    string MaHoa(string chuoiCanMaHoa)
    {
        byte[] data = Encoding.ASCII.GetBytes(chuoiCanMaHoa);
        SHA512 sha5 = new SHA512Managed();
        byte[] result = sha5.ComputeHash(data);
        string chuoiMaHoa = Encoding.ASCII.GetString(result);
        return chuoiMaHoa;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Tim-kiem.aspx?tk=" + txtsearch.Text);
    }
}